import os,random
from django.shortcuts import render, redirect
from django.views import View
from django.http import FileResponse,HttpResponseForbidden
from .forms import FileForm, ShareForm
from .models import File
from django.contrib.auth.decorators import login_required
# Create your views here.

SHARE_CODE_LENGTH = 6
SHARE_CODE_CHARS = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
def index(request):
    return render(request, 'index.html', {'user_login': request})
@login_required(login_url='auth:login')
def upload(request):
    if request.method == 'POST':
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            obj=form.save(commit=False)
            obj.upload_user = request.user
            obj.type = request.FILES['file_path'].content_type
            obj.size = f'{request.FILES['file_path'].size} bytes'
            obj.name = request.FILES['file_path'].name
            obj.save()
            return render(request, 'upload.html', {'form': form, 'success': True})
    else:
        form = FileForm()
        return render(request, 'upload.html', {'form': form})
@login_required(login_url='auth:login')
def list(request):
    files = File.objects.filter(upload_user=request.user)
    return render(request, 'list.html', {'files': files})
@login_required(login_url='auth:login')
def delete(request, file_id):
    file = File.objects.get(id=file_id)
    if file.upload_user != request.user:
        return HttpResponseForbidden()
    file_path = file.file_path.path
    os.remove(file_path)
    file.delete()
    return redirect('cloud_store_app:list')
@login_required(login_url='auth:login')
def download(request, file_id):
    file = File.objects.get(id=file_id)
    if file.upload_user != request.user:
        return HttpResponseForbidden()
    response = FileResponse(file.file_path.open(), as_attachment=True)
    return response
@login_required(login_url='auth:login')
def share(request, file_id):
    file = File.objects.get(id=file_id)
    file.share_code = ''.join(random.sample(SHARE_CODE_CHARS, SHARE_CODE_LENGTH))
    share_url = request.build_absolute_uri('share_download')
    file.save()
    return render(request, 'share.html', {'share_code': file.share_code, 'share_url': share_url})
@login_required(login_url='auth:login')
def share_download(request,file_id):
    if request.method != 'POST':
        form = ShareForm()
        return render(request, 'share_download.html', {'form': form})
    else:
        form = ShareForm(request.POST, request.FILES)
        share_code = request.POST.get('share_pass')
        if form.is_valid() and File.objects.filter(share_code=share_code).exists():
            file = File.objects.get(share_code=share_code)
            response = FileResponse(file.file_path.open(), as_attachment=True)
            return response
        else:
            return render(request, 'share_download.html', {'form': form, 'error': '分享码错误'})